package com.qf.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * 全局过滤器
 *   1、登录
 *   2、鉴权
 *
 *
 *   网关全局过滤器  默认自带9个  有用 Spring框架自己要使用的
 *     自带9个  + 自定义1个  == 10个过滤器
 * @author lixu
 */
@Component
public class GlobalLoginFilter implements GlobalFilter, Ordered {

    public static final String TOKEN = "token";//
    /**
     * 全局过滤器执行方法
     *    1、Tomcat  请求 request  响应 response  Servlet
     *    2、WebFlux 请求 request  响应 response
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {


        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1:当前请求路径
        String uri = request.getURI().toString();
        System.out.println("uri:" + uri);
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();

        System.out.println("ip:" + request.getRemoteAddress().getHostString());
        //2:判断用户是否登录
        //3:获取请求头中的token令牌是否存在
        HttpHeaders headers = request.getHeaders();
        //令牌集合  token:  相当于  cookie的Id   cookie:jessionid:trewtrwtwertwetwretew
        //请求头：  token:trewtrwtwertwetwretew
    /*    List<String> tokenList = headers.get(TOKEN);
        if(null != tokenList && tokenList.size() > 0){
            //令牌是存在 的

        }*/
        //获取上面List<String> 的0角标的数据
        String token = headers.getFirst(TOKEN);
        if(StringUtils.isEmpty(token)){
            //表示token是没有的
            //未登录
            System.out.println("用户未登录");
            //Vue的页面
            //返回数据JSON {error:0,msg:成功}  Vue页面上接收到了JSOn  Vue判断是1之后自己跳转到登录页面
            //返回数据JSON {error:1,msg:未登录}  Vue页面上接收到了JSOn  Vue判断是1之后自己跳转到登录页面
            //返回数据JSON {error:2,msg:没有权限}  Vue页面上接收到了JSOn  Vue判断是2之后自己跳转到提示用户没有权限页面

            Map map = new HashMap<>();
            map.put("error","1");
            map.put("msg","未登录");
            ObjectMapper objectMapper = new ObjectMapper();
            String json = null;
            try {
                json = objectMapper.writeValueAsString(map);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            DataBufferFactory dataBufferFactory = response.bufferFactory();
            DataBuffer wrap = dataBufferFactory.wrap(json.getBytes());
            //响应头中设置了编码
            response.getHeaders().add(
                    HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON_UTF8_VALUE);
            //响应流
            //response:WebFlux的技术
            return response.writeWith(Mono.just(wrap));
        }
        //不拦截 直接放行
        return chain.filter(exchange);
    }

    /**
     * 全局过滤器的执行顺序
     *
     *  默认是0 ：  值越小优先级越高
     *
     *    - Integer.MAX_VALUE  ~ 0  ~1 ~  Integer.MAX_VALUE
     *
     * @return
     */
    @Override
    public int getOrder() {
        System.out.println(Integer.MIN_VALUE);
        System.out.println(Integer.MAX_VALUE);
        return 0;
    }
}
